import tkinter as tk
from tkinter import ttk, messagebox
from GUI界面.BaseSubWindow import BaseSubWindow
from 数据库操作.UserOperation import UserOperation
from 数据库操作.CreateMysqlCon import CreateMysqlCon

class UserManage(BaseSubWindow):
    """用户列表以及管理"""
    def create_widgets(self):
        # 创建标题
        ttk.Label(self, text="用户管理", font=('Arial', 16)).pack(pady=10)
        
        # 创建用户列表框架
        list_frame = ttk.Frame(self)
        list_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
        
        # 创建滚动条
        scrollbar = ttk.Scrollbar(list_frame)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        
        # 创建用户列表
        self.user_tree = ttk.Treeview(list_frame, 
                                    columns=("id", "username", "age", "gender"), 
                                    show="headings",
                                    yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.user_tree.yview)
        
        # 配置列
        self.user_tree.column("id", width=50)
        self.user_tree.column("username", width=150)
        self.user_tree.column("age", width=50)
        self.user_tree.column("gender", width=50)
        
        # 设置列标题
        self.user_tree.heading("id", text="ID")
        self.user_tree.heading("username", text="用户名")
        self.user_tree.heading("age", text="年龄")
        self.user_tree.heading("gender", text="性别")
        
        # 填充数据
        self.refresh_user_list()
        
        self.user_tree.pack(fill=tk.BOTH, expand=True)
        
        # 绑定双击事件
        self.user_tree.bind("<Double-1>", self.edit_user)
        
        # 按钮框架
        button_frame = ttk.Frame(self)
        button_frame.pack(pady=10)
        
        # 刷新按钮
        refresh_button = ttk.Button(button_frame, text="刷新列表", command=self.refresh_user_list)
        refresh_button.pack(side=tk.LEFT, padx=5)
        
        # 编辑按钮
        edit_button = ttk.Button(button_frame, text="编辑用户", command=lambda: self.edit_user(None))
        edit_button.pack(side=tk.LEFT, padx=5)
        
        # 删除按钮
        delete_button = ttk.Button(button_frame, text="删除用户", command=self.delete_user)
        delete_button.pack(side=tk.LEFT, padx=5)
    
    def refresh_user_list(self):
        """刷新用户列表"""
        # 清空现有数据
        for item in self.user_tree.get_children():
            self.user_tree.delete(item)
            
        try:
            # 获取并显示数据
            user_op = UserOperation()
            users = user_op.get_all_users()
            
            print(f"获取到的用户数据: {users}")
            
            for user in users:
                # 转换性别显示
                gender_display = "男" if user[3] == 0 else "女"
                print(f"插入用户: ID={user[0]}, 用户名={user[1]}, 年龄={user[2]}, 性别={gender_display}")
                self.user_tree.insert("", "end", values=(user[0], user[1], user[2], gender_display))
        except Exception as e:
            messagebox.showerror("错误", f"刷新用户列表失败: {e}")
            print(f"刷新用户列表失败: {e}")
    
    def edit_user(self, event):
        """编辑用户信息"""
        # 获取选中项
        if event:  # 双击事件
            selected_items = [self.user_tree.selection()[0]]
        else:  # 按钮点击事件
            selected_items = self.user_tree.selection()
            
        if not selected_items:
            messagebox.showwarning("警告", "请先选择要编辑的用户")
            return
        
        # 只编辑第一个选中的用户
        item = selected_items[0]
        user_data = self.user_tree.item(item, "values")
        print(f"选中的用户数据: {user_data}")
        
        # 创建编辑窗口
        self.edit_window = tk.Toplevel(self)
        self.edit_window.title("编辑用户信息")
        self.edit_window.geometry("300x200")
        self.edit_window.resizable(False, False)
        
        # 用户ID（不可编辑）
        ttk.Label(self.edit_window, text="用户ID:").grid(row=0, column=0, padx=10, pady=5, sticky="e")
        id_var = tk.StringVar(value=user_data[0])
        ttk.Entry(self.edit_window, textvariable=id_var, state="readonly").grid(row=0, column=1, padx=10, pady=5, sticky="w")
        
        # 用户名（不可编辑）
        ttk.Label(self.edit_window, text="用户名:").grid(row=1, column=0, padx=10, pady=5, sticky="e")
        self.username_var = tk.StringVar(value=user_data[1])
        username_entry = ttk.Entry(self.edit_window, textvariable=self.username_var, state="readonly")
        username_entry.grid(row=1, column=1, padx=10, pady=5, sticky="w")
        
        # 年龄
        ttk.Label(self.edit_window, text="年龄:").grid(row=2, column=0, padx=10, pady=5, sticky="e")
        self.age_var = tk.StringVar(value=user_data[2])
        ttk.Entry(self.edit_window, textvariable=self.age_var).grid(row=2, column=1, padx=10, pady=5, sticky="w")
        
        # 性别
        ttk.Label(self.edit_window, text="性别:").grid(row=3, column=0, padx=10, pady=5, sticky="e")
        self.gender_var = tk.StringVar(value=user_data[3])
        gender_combo = ttk.Combobox(self.edit_window, textvariable=self.gender_var, values=["男", "女"], state="readonly")
        gender_combo.grid(row=3, column=1, padx=10, pady=5, sticky="w")
        
        # 按钮框架
        button_frame = ttk.Frame(self.edit_window)
        button_frame.grid(row=4, column=0, columnspan=2, pady=10)
        
        # 保存按钮
        save_button = ttk.Button(button_frame, text="保存", 
                               command=lambda: self.save_user_info(id_var.get()))
        save_button.pack(side=tk.LEFT, padx=5)
        
        # 取消按钮
        cancel_button = ttk.Button(button_frame, text="取消", 
                                 command=self.edit_window.destroy)
        cancel_button.pack(side=tk.LEFT, padx=5)
    
    def save_user_info(self, user_id):
        """保存用户信息"""
        try:
            # 验证年龄
            try:
                age = int(self.age_var.get())
                if age <= 0 or age > 120:
                    messagebox.showwarning("警告", "请输入有效的年龄（1-120）")
                    return
            except ValueError:
                messagebox.showwarning("警告", "年龄必须是数字")
                return
            
            # 保存用户信息
            user_op = UserOperation()
            if user_op.update_user_info(user_id, age, self.gender_var.get()):
                messagebox.showinfo("成功", "用户信息更新成功")
                self.edit_window.destroy()
                self.refresh_user_list()
            else:
                messagebox.showerror("错误", "用户信息更新失败")
        except Exception as e:
            messagebox.showerror("错误", f"保存用户信息失败: {e}")
            print(f"保存用户信息失败: {e}")
    
    def delete_user(self):
        """删除用户"""
        # 获取选中项
        selected_items = self.user_tree.selection()
        if not selected_items:
            messagebox.showwarning("警告", "请先选择要删除的用户")
            return
        
        # 检查是否是当前登录用户
        for item in selected_items:
            user_data = self.user_tree.item(item, "values")
            if user_data[1] == self.user.username:
                messagebox.showwarning("警告", "不能删除当前登录的用户")
                return
        
        # 确认删除
        if not messagebox.askyesno("确认", "确定要删除选中的用户吗？此操作不可恢复！"):
            return
        
        # 执行删除
        user_op = UserOperation()
        for item in selected_items:
            user_data = self.user_tree.item(item, "values")
            user_id = user_data[0]
            username = user_data[1]
            
            success, message = user_op.delete_user(user_id)
            if success:
                self.user_tree.delete(item)
                messagebox.showinfo("成功", f"用户 {username} 已删除")
            else:
                messagebox.showerror("错误", message)
        
        # 刷新用户列表
        self.refresh_user_list()